package com.iwhalecloud.bss.kite.cucc.service.util;

import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.ztesoft.bss.common.util.SpringUtil;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Objects;

/**
 * @Description 根据协议月租、标准月租计算折扣
 * @Author wu.siru
 * @Date 2021/11/19
 */
public class CalculateDiscountsUtil {

    public static void calculateDiscounts(String sceneInstId, KiteInst inst) {
        OperateInstAttrService operateInstAttrService = SpringUtil.getBean(OperateInstAttrService.class);
        //标准月租
        KiteAttr standardTariffsAttr = inst.getAttr("200001354");
        //协议月租
        KiteAttr agreementMonthlyRentAttr = inst.getAttr("200000169");
        //折扣
        KiteAttr discountAttr = inst.getAttr("200001352");

        //存在折扣属性且标准资费、协议资费不为空
        if (Objects.nonNull(discountAttr) && Objects.nonNull(standardTariffsAttr) && Objects.nonNull(agreementMonthlyRentAttr)
            && KiteStringUtils.isNotEmpty(standardTariffsAttr.getValue()) && KiteStringUtils.isNotEmpty(agreementMonthlyRentAttr.getValue())
            && !"0".equals(standardTariffsAttr.getValue())) {
            BigDecimal agreedTariffsPrice = new BigDecimal(agreementMonthlyRentAttr.getValue());
            BigDecimal standardTariffsPrice = new BigDecimal(standardTariffsAttr.getValue());
            Double discount = agreedTariffsPrice.divide(standardTariffsPrice, 4, BigDecimal.ROUND_HALF_UP).doubleValue();
            NumberFormat percent = NumberFormat.getPercentInstance();
            percent.setMaximumFractionDigits(4);
            percent.setGroupingUsed(false);
            String discountStr = KiteStringUtils.valueOf(percent.format(discount));
            //折扣
            operateInstAttrService.setAttrValue(inst, "200001352", discountStr, sceneInstId, null);
        } else {
            operateInstAttrService.setAttrValue(inst, "200001352", "", sceneInstId, null);
        }
    }

    public static void calculateDiscounts(String sceneInstId, String custId, String offerInstId) {
        KiteOfferInst additionalKiteOfferInst = SpringUtil.getBean(IQuerySceneInstService.class).getOfferInst(custId, offerInstId);
        if (Objects.isNull(additionalKiteOfferInst)) {
            return;
        }
        calculateDiscounts(sceneInstId, additionalKiteOfferInst);
    }
}
